//
//  VersionManager.swift
//  ezyform
//
//  Created by Hubert on 2022/4/27.
//  Copyright © 2022 Client.Solution Pty Ltd. All rights reserved.
//

import Foundation
import UIKit
class VersionManager: NSObject {
    static let shared = VersionManager()
    
    func checkForceUpdateVersion(){
        if Connectivity.isConnectedToInternet {
            let vm = CommanViewModel()
            vm.setBlockAfterNetwork {  [weak self] (obj, _) -> Void in
                guard let self = self else { return }
                var isCheck: Bool = false
                if let results = obj as? NSDictionary {//
                    let dic = Bundle.main.infoDictionary
                    if let days = results.object(forKey: "update_reminder_frequency") as? Int {
                        UserDefaults.standard.set(days, forKey: "update_reminder_frequency")
                    }
                    if let forceUpdateVersions = results.object(forKey: "forced_update_versions") as? String, let currentAppVersion = dic!["CFBundleShortVersionString"] as? String, let latestVersion = results.object(forKey: "version") as? String,  forceUpdateVersions.count > 0{
                        //加上；是为了防止3.3.1和3.3.10版本
                        if forceUpdateVersions.contains(currentAppVersion + ";") {
                            let msg = results.object(forKey: "description") as? String
                            Tool().forceUpgradeFromAppStore(title: R.string.localizable.newVersion(latestVersion), message: msg ?? "")
                        }else{
                            isCheck = true
                        }
                    }else{
                        isCheck = true
                    }
                }else{//返回的data是null，表示后台没有配置App Version的信息
                    isCheck = true
                }
                if isCheck {
                    self.checkAPPLatestVersion()
                }
            } errorBlock: { (_,_) in
                
            }

            vm.checkAPPForceUpdateVersion()
        }
    }
    func checkAPPLatestVersion(){
        if Connectivity.isConnectedToInternet {
            let vm = CommanViewModel()
            vm.checkAPPLatestVersion { obj, code, msg in
                if let resultDic = obj as?  NSDictionary, let results = resultDic.object(forKey: "results") as? NSArray, results.count > 0 {
                    if let versionInfo = results.firstObject as? NSDictionary {
                        let dic = Bundle.main.infoDictionary
                        if let currentAppVersion = dic!["CFBundleShortVersionString"] as? String, let appVersionOnStore = versionInfo.object(forKey: "version") as? String {

                            if self.compareVersion(appVersionOnStore, currentAppVersion) {
                                APPConfig.loginInfo.appVersionInfo = R.string.localizable.upgradeToTheLatestVersion(appVersionOnStore)
                                var currentAppVersionShowFlag: Bool = true//是否提示当前版本，默认提示
                                //Apple Store上的版本以前有提示用户更新，现在距离上次提示大于等于设置的提示频率，默认是一天一次
                                if  let lastTipDate = UserDefaults.standard.object(forKey: appVersionOnStore) as? Date {
                                    currentAppVersionShowFlag = DateUtil().getInternalToNow(fromDate: lastTipDate)//超过一天就提示
                                }
                                //需要提示：
                                if currentAppVersionShowFlag {
                                    UserDefaults.standard.set(Date(), forKey: appVersionOnStore)
                                    let releaseNotes = versionInfo.object(forKey: "releaseNotes") as? String
                                    Tool().upgradeFromAppStore(title: R.string.localizable.newVersion(appVersionOnStore), message: releaseNotes ?? "")
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    //MARK: - 判断当前版本是否小于线上版本
    private func compareVersion(_ online: String, _ local: String) -> Bool {
        let onlineArr = online.components(separatedBy: ".")
        let localArr = local.components(separatedBy: ".")
        let count = onlineArr.count > localArr.count ? onlineArr.count : localArr.count
        for i in 0..<count {
            var a = 0, b = 0
            if i < onlineArr.count {
                a = Int(onlineArr[i]) ?? 0
            }
            if i < localArr.count {
                b = Int(localArr[i]) ?? 0
            }
            if a > b {
                return true
            }else if a < b{
                return false
            }
        }
        return false
    }
}
